<?php


namespace app\api\model;


use app\lib\exception\BaseException;
use think\Db;
use think\Exception;
use think\Model;
use think\Request;

class BookModel extends Model
{
    protected $table = 'cash_book';

    public static function getBooks($month){
        return Db::query("select * from cash_book where month = ? order by category asc, id asc", [$month]);
    }

    public static function saveBook($month, $title)
    {
        $book = new BookModel;
        $book->data([
            'title'  =>  $title,
            'month' => $month,
            'category' =>  'B',
            'state' => 2,
            'is_merge' => 1
        ]);
        try {
            $book->save();
            return self::getBooks($month);
        }catch (Exception $e){
            throw new BaseException([
                'msg' => '此账本名称在B类账本中已存在.',
                'code' => 9527,
                'errorCode' => 400
            ]);
        }

    }

    public static function updateBookStates(Request $request)
    {
        $parmas = $request->post();
        $month = $parmas['month'];
        $books = $parmas['books'];
        foreach ($books as $book){
            if($book['state'] == 2){
                InfoModel::getInfoWithBook($month, $book['id']);
            }
            BookModel::where('id', $book['id'])->update(['state' => $book['state']]);
        }
    }

}